package demo.xiaxl.com.android_demo.pagersnaphelper;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;

public class NestedListView extends ListView {
    private final String TAG = "NestedListView";
    public boolean noMoreData;
    private float lastY;

    public NestedListView(Context context) {
        super(context);
    }

    public NestedListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NestedListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean disallowParentIntercept = true;
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastY = ev.getY();
                Log.i(TAG, "ACTION_DOWN y: " + lastY);
                break;
            case MotionEvent.ACTION_MOVE:
                float y = ev.getY();
                if (y < lastY && isListViewReachBottom()) {
                    // scroll from bottom to top and reach bottom
                    disallowParentIntercept = false;
                    Log.i(TAG, "ACTION_MOVE up");
                } else if (y > lastY && isListViewReachTop()) {
                    // scroll from top to bottom and reach top
                    disallowParentIntercept = false;
                    Log.i(TAG, "ACTION_MOVE down");
                }
                break;
            default:
                break;
        }
        getParent().requestDisallowInterceptTouchEvent(disallowParentIntercept);
        return super.dispatchTouchEvent(ev);
    }

    public boolean isListViewReachTop() {
        boolean reachTop = false;
        if (this.getFirstVisiblePosition() == 0) {
            final View topChildView = this.getChildAt(0);
            reachTop = topChildView.getTop() >= 0;
        }
        Log.i(TAG, "isListViewReachTop: " + reachTop);
        return reachTop;
    }

    public boolean isListViewReachBottom() {
        boolean reachBottom = false;
        if (this.getLastVisiblePosition() == (this.getCount() - 1)) {
            final View bottomChildView = this.getChildAt(this.getLastVisiblePosition() - this.getFirstVisiblePosition());
            reachBottom = (this.getHeight() >= bottomChildView.getBottom());
        }
        reachBottom = reachBottom && noMoreData;
        Log.i(TAG, "isListViewReachBottom: " + reachBottom);
        return reachBottom;
    }
}
